package com.night.administration.service.impl;

import com.night.administration.excepyion.AreaConflictException;
import com.night.administration.excepyion.TeacherTimeConflictException;
import com.night.administration.mapper.TestMapper;
import com.night.administration.service.TestService;
import com.night.common.entity.administration.Course;
import com.night.common.entity.administration.Teacher;
import com.night.common.entity.administration.Test;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TestServiceImpl
 * @Description: //TODO
 * @author: LZJ
 * @date: 2022/10/19-22:15
 * @version: v1.0
 */
@Service("TestService")
@Transactional
public class TestServiceImpl implements TestService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private TestMapper testMapper;

    @Override
    public void insert(Test test) throws AreaConflictException, TeacherTimeConflictException {
        List<Test> ts = testMapper.getArea(test.getTestStartTime());
        for (Test t : ts) {
            if (t.getArea().getId() == test.getArea().getId()) {
                throw new AreaConflictException("教室已被占用");
            }
        }
        List<Test> tests = testMapper.getTestByTeacherId(test.getTeacher().getId());
        for (Test test1 : tests) {
            if (test1.getTestStartTime().compareTo(test.getTestStartTime()) == 0) {
                throw new TeacherTimeConflictException("监考教师的时间冲突");
            }
        }
        testMapper.insert(test);
    }

    @Override
    public void update(Test test) {
        testMapper.update(test);
    }

    @Override
    public void deleted(int id) {
        testMapper.deleted(id);
    }

    @Override
    public List<Test> getByCondition(Test test) {
        String key = "test";
        List<Test> tests;
        if (test.getTeacher() == null) {
            Teacher teacher = new Teacher();
            teacher.setName("");
            test.setTeacher(teacher);
        }
        if (test.getCourse() == null) {
            Course course = new Course();
            course.setCourseName("");
            test.setCourse(course);
        }
        tests = (List<Test>) redisTemplate.opsForValue().get(key);
        if (tests == null) {
            tests = testMapper.getByCondition(test);
            redisTemplate.opsForValue().set(key, tests, 30, TimeUnit.SECONDS);
        }
        return tests;
    }

    @Override
    public List<Test> getTestByTeacherId(int teacherId) {
        return testMapper.getTestByTeacherId(teacherId);
    }
}
